import UsersApi from '../services/users'

export default {
  namespace: 'global',

  state: {
    language: 'zh_CN',
    userInfo: null,
    userRole: ['guest'],
    userMenu: ['/home', '/home/CaeTools'],
    collapsed: false,
  },

  effects: {
    * queryUserInfo({ payload }, { call, put }) {
      const { userName } = payload
      const response = yield call(UsersApi.userInfo, userName)
      yield put({
        type: 'saveUserInfo',
        payload: response.data,
      })
      yield put({
        type: 'queryUserRole',
        payload: response.data.id,
      })
      yield put({
        type: 'queryUserResource',
        payload: response.data.id,
      })
    },
    * queryUserRole({ payload }, { call, put }) {
      const response = yield call(UsersApi.roles, payload)
      yield put({
        type: 'saveUserRole',
        payload: response,
      })
    },
    * queryUserResource({ payload }, { call, put }) {
      const response = yield call(UsersApi.resources, payload)
      yield put({
        type: 'saveUserResource',
        payload: response,
      })
    },
  },

  reducers: {
    clear(state) {
      return {
        ...state,
        userInfo: null,
        userRole: 'guest',
        userMenu: ['/system', '/system/about'],
      }
    },
    saveLanguage(state, { payload }) {
      return {
        ...state,
        language: payload,
      }
    },
    saveUserInfo(state, { payload }) {
      return {
        ...state,
        userInfo: {
          ...payload,
          password: '',
        },
      }
    },
    saveUserResource(state, { payload }) {
      const resources = []
      payload.data.map(item => resources.push(item.name))
      return {
        ...state,
        userMenu: resources,
      }
    },
    saveUserRole(state, { payload }) {
      const roles = []
      payload.data.map(item => roles.push(item.name))
      return {
        ...state,
        userRole: roles,
      }
    },
    changeLayoutCollapsed(state) {
      return {
        ...state,
        collapsed: !state.collapsed,
      }
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
    },
  },
}
